home *** CD-ROM | disk | FTP | other *** search
/ The 640 MEG Shareware Studio 2 / The 640 Meg Shareware Studio CD-ROM Volume II (Data Express)(1993).ISO / clang / c_course.zip / CHAP12.TXT < prev    next >
Text File  |  1989-12-30  |  27KB  |  587 lines

  1.                       Chapter 12 - Dynamic Allocation
  2.  
  3.  
  4.                         WHAT IS DYNAMIC ALLOCATION?
  5.  
  6.              Dynamic allocation is very intimidating to a person the 
  7.         first time he comes across it, but that need not be.  Simply 
  8.         relax  and  read this chapter carefully and you will have  a 
  9.         good grounding in a very valuable programming resource.  All 
  10.         of the variables in every program up to this point have been 
  11.         static  variables as far as we  are  concerned.   (Actually, 
  12.         some  of  them  have been "automatic" and  were  dynamically 
  13.         allocated for you by the system,  but it was transparent  to 
  14.         you.)   In  this  chapter,  we will study  some  dynamically 
  15.         allocated variables.   They are simply variables that do not 
  16.         exist   when  the  program  is  loaded,   but  are   created 
  17.         dynamically as they are needed.  It is possible, using these 
  18.         techniques, to create as many variables as needed, use them, 
  19.         and deallocate their space for use by other  variables.   As 
  20.         usual,  the best teacher is an example,  so load and display 
  21.         the program named DYNLIST.C.
  22.  
  23.              We  begin by defining a named structure "animal" with a 
  24.         few  fields  pertaining  to dogs.   We  do  not  define  any 
  25.         variables of this type,  only three pointers.  If you search 
  26.         through  the  remainder  of the program,  you will  find  no 
  27.         variables defined so we have nothing to store data in.   All 
  28.         we have to work with are three pointers, each of which point 
  29.         to the defined structure.   In order to do anything, we need 
  30.         some variables, so we will create some dynamically.
  31.  
  32.                          DYNAMIC VARIABLE CREATION
  33.  
  34.              The first program statement, which assigns something to 
  35.         the   pointer  "pet1"  will  create  a   dynamic   structure 
  36.         containing  three variables.   The heart of the statement is 
  37.         the "malloc" function buried in the middle of the statement.  
  38.         This  is a "memory allocate" function that needs  the  other 
  39.         things to completely define it.   The "malloc" function,  by 
  40.         default, will allocate a piece of memory on a "heap" that is 
  41.         "n" characters in length and will be of type character.  The 
  42.         "n"  must be specified as the only argument to the function.  
  43.         We will discuss "n" shortly,  but first we need to define  a 
  44.         "heap".
  45.  
  46.                               WHAT IS A HEAP?
  47.  
  48.              Every compiler has a set of limitations on it as to how 
  49.         big  the executable file can be,  how many variables can  be 
  50.         used,  how long the source file can be, etc.  One limitation 
  51.         placed  on  users  by  many compilers  for  the  IBM-PC  and 
  52.         compatibles is a limit of 64K for the executable code.  This 
  53.         is  because  the  IBM-PC uses a microprocessor  with  a  64K 
  54.         segment  size,  and  it requires special calls to  use  data 
  55.  
  56.  
  57.                                   Page 83
  58.  
  59.  
  60.  
  61.  
  62.  
  63.  
  64.  
  65.  
  66.  
  67.                       Chapter 12 - Dynamic Allocation
  68.  
  69.  
  70.         outside  of a single segment.   In order to keep the program 
  71.         small  and  efficient,  these calls are not  used,  and  the 
  72.         program is limited but still adequate for most programs. 
  73.  
  74.              A  heap is an area outside of this 64K  boundary  which 
  75.         can  be accessed by the program to store data and variables.  
  76.         The  data and variables are put on the "heap" by the  system 
  77.         as  calls to "malloc" are made.   The system keeps track  of 
  78.         where  the  data  is stored.   Data  and  variables  can  be 
  79.         deallocated  as desired leading to holes in the  heap.   The 
  80.         system  knows  where  the holes are and will  use  them  for 
  81.         additional  data  storage as more "malloc" calls  are  made.  
  82.         The  structure  of  the  heap is therefore  a  very  dynamic 
  83.         entity, changing constantly.
  84.  
  85.                             MORE ABOUT SEGMENTS
  86.  
  87.              Some  of the more expensive compilers give the  user  a 
  88.         choice  of memory models to use.   Examples are Lattice  and 
  89.         Microsoft,  which  allow the programmer a choice of using  a 
  90.         model  with  a  64K  limitation on  program  size  but  more 
  91.         efficient  running,  or using a model with a 640K limitation 
  92.         and requiring longer address calls leading to less efficient 
  93.         addressing.   Using the larger address space requires  inter 
  94.         segment  addressing resulting in the slightly slower running 
  95.         time.   The time is probably insignificant in most programs, 
  96.         but there are other considerations.
  97.  
  98.              If  a program uses no more than 64K bytes for the total 
  99.         of its code and memory and if it doesn't use a stack, it can 
  100.         be made into a .COM file.  Since a .COM file is already in a 
  101.         memory image format, it can be loaded very quickly whereas a 
  102.         file  in a .EXE format must have its addresses relocated  as 
  103.         it is loaded.  Therefore a small memory model can generate a 
  104.         program  that loads faster than one generated with a  larger 
  105.         memory model.   Don't let this worry you, it is a fine point 
  106.         that few programmers worry about.
  107.  
  108.              Using dynamic allocation,  it is possible to store  the 
  109.         data  on  the "heap" and that may be enough to allow you  to 
  110.         use the small memory model.   Of course,  you wouldn't store 
  111.         local  variables such as counters and indexes on  the  heap, 
  112.         only very large arrays or structures. 
  113.  
  114.              Even  more  important than the need to stay within  the 
  115.         small memory model is the need to stay within the  computer.  
  116.         If  you  had a program that used several large data  storage 
  117.         areas,  but not at the same time,  you could load one  block 
  118.         storing  it  dynamically,  then get rid of it and reuse  the 
  119.         space for the next large block of data.  Dynamically storing 
  120.         each block of data in succession, and using the same storage 
  121.  
  122.  
  123.                                   Page 84
  124.  
  125.  
  126.  
  127.  
  128.  
  129.  
  130.  
  131.  
  132.  
  133.                       Chapter 12 - Dynamic Allocation
  134.  
  135.  
  136.         for  each block may allow you to run your entire program  in 
  137.         the computer without breaking it up into smaller programs. 
  138.  
  139.                        BACK TO THE "MALLOC" FUNCTION
  140.  
  141.              Hopefully  the above description of the "heap" and  the 
  142.         overall plan for dynamic allocation helped you to understand 
  143.         what  we are doing with the "malloc"  function.   It  simply 
  144.         asks the system for a block of memory of the size specified, 
  145.         and  gets  the block with the pointer pointing to the  first 
  146.         element of the block.   The only argument in the parentheses 
  147.         is the size of the block desired and in our present case, we 
  148.         desire  a  block  that will hold one of  the  structures  we 
  149.         defined at the beginning of the program.   The "sizeof" is a 
  150.         new function,  new to us at least,  that returns the size in 
  151.         bytes of the argument within its parentheses.  It therefore, 
  152.         returns  the size of the structure named animal,  in  bytes, 
  153.         and  that  number is sent to the system  with  the  "malloc" 
  154.         call.   At  the completion of that call,  we have a block on 
  155.         the  heap allocated to us,  with pet1 pointing to the  first 
  156.         byte of the block.     
  157.  
  158.                               WHAT IS A CAST?
  159.  
  160.              We  still  have  a  funny  looking  construct  at   the 
  161.         beginning  of the "malloc" function call.   That is called a 
  162.         "cast".   The  "malloc"  function returns a block  with  the 
  163.         pointer  pointing  to it being a pointer of type  "char"  by 
  164.         default.  Many times, if not most, you do not want a pointer 
  165.         to a "char" type variable,  but to some other type.  You can 
  166.         define  the  pointer type with the construct  given  on  the 
  167.         example line.   In this case we want the pointer to point to 
  168.         a  structure of type "animal",  so we tell the compiler with 
  169.         this strange looking construct.   Even if you omit the cast, 
  170.         most compilers will return a pointer correctly,  give you  a 
  171.         warning,  and  go  on to produce a working program.   It  is 
  172.         better programming practice to provide the compiler with the 
  173.         cast to prevent getting the warning message.
  174.  
  175.                 USING THE DYNAMICALLY ALLOCATED MEMORY BLOCK
  176.  
  177.              If you remember our studies of structures and pointers, 
  178.         you  will recall that if we have a structure with a  pointer 
  179.         pointing  to it,  we can access any of the variables  within 
  180.         the structure.   In the next three lines of the program,  we 
  181.         assign  some silly data to the structure  for  illustration.  
  182.         It  should come as no surprise to you that these  assignment 
  183.         statements  look just like assignments to statically defined 
  184.         variables.
  185.  
  186.  
  187.  
  188.  
  189.                                   Page 85
  190.  
  191.  
  192.  
  193.  
  194.  
  195.  
  196.  
  197.  
  198.  
  199.                       Chapter 12 - Dynamic Allocation
  200.  
  201.  
  202.              In the next statement, we assign the value of "pet1" to 
  203.         "pet2" also.   This creates no new data,  we simply have two 
  204.         pointers  to the same object.   Since "pet2" is pointing  to 
  205.         the structure we created above,  "pet1" can be reused to get 
  206.         another  dynamically allocated structure which is just  what 
  207.         we  do next.   Keep in mind that "pet2" could have  just  as 
  208.         easily been used for the new allocation.   The new structure 
  209.         is filled with silly data for illustration.
  210.  
  211.              Finally,  we  allocate another block on the heap  using 
  212.         the  pointer  "pet3",  and fill its block with  illustrative 
  213.         data.
  214.  
  215.              Printing  the  data out should pose no problem  to  you 
  216.         since  there is nothing new in the three  print  statements.  
  217.         It is left for you to study.
  218.  
  219.                GETTING RID OF THE DYNAMICALLY ALLOCATED DATA
  220.  
  221.              Another new function is used to get rid of the data and 
  222.         free  up  the  space on the heap  for  reuse,  the  function 
  223.         "free".   To use it,  you simply call it with the pointer to 
  224.         the   block  as  the  only  argument,   and  the  block   is 
  225.         deallocated.
  226.  
  227.              In  order  to illustrate another aspect of the  dynamic 
  228.         allocation and deallocation of data,  an additional step  is 
  229.         included in the program on your monitor.  The pointer "pet1" 
  230.         is assigned the value of "pet3".   In doing this,  the block 
  231.         that  "pet1" was pointing to is effectively lost since there 
  232.         is  no pointer that is now pointing to that block.   It  can 
  233.         therefore never again be referred to,  changed,  or disposed 
  234.         of.   That memory,  which is a block on the heap,  is wasted 
  235.         from  this point on.   This is not something that you  would 
  236.         ever  purposely do in a program.   It is only done here  for 
  237.         illustration.
  238.  
  239.              The  first  "free" function call removes the  block  of 
  240.         data that "pet1" and "pet3" were pointing to, and the second 
  241.         "free"  call  removes  the block of  data  that  "pet2"  was 
  242.         pointing  to.   We therefore have lost access to all of  our 
  243.         data  generated earlier.   There is still one block of  data 
  244.         that  is on the heap but there is no pointer to it since  we 
  245.         lost  the address to it.   Trying to "free" the data pointed 
  246.         to by "pet1" would result in an error because it has already 
  247.         been  "freed"  by the use of "pet3".   There is no  need  to 
  248.         worry,  when  we  return to DOS,  the entire  heap  will  be 
  249.         disposed  of with no regard to what we have put on it.   The 
  250.         point  does need to made that losing a pointer to a block of 
  251.         the  heap,  forever removes that block of data storage  from 
  252.         our program and we may need that storage later.
  253.  
  254.  
  255.                                   Page 86
  256.  
  257.  
  258.  
  259.  
  260.  
  261.  
  262.  
  263.  
  264.  
  265.                       Chapter 12 - Dynamic Allocation
  266.  
  267.  
  268.  
  269.              Compile and run the program to see if it does what  you 
  270.         think it should do based on this discussion.
  271.  
  272.                         THAT WAS A LOT OF DISCUSSION
  273.  
  274.              It took nearly four pages to get through the discussion 
  275.         of  the last program but it was time well spent.   It should 
  276.         be  somewhat exciting to you to know that there  is  nothing 
  277.         else to learn about dynamic allocation,  the last four pages 
  278.         covered  it all.   Of course,  there is a lot to learn about 
  279.         the  technique  of using dynamic allocation,  and  for  that 
  280.         reason,  there  are two more files to study.   But the  fact 
  281.         remains,  there  is  nothing  more to  learn  about  dynamic 
  282.         allocation than what was given so far in this chapter.
  283.  
  284.                             AN ARRAY OF POINTERS
  285.  
  286.              Load and display the file BIGDYNL.C for another example 
  287.         of dynamic allocation.   This program is very similar to the 
  288.         last one since we use the same structure,  but this time  we 
  289.         define an array of pointers to illustrate the means by which 
  290.         you  could build a large database using an array of pointers 
  291.         rather  than a single pointer to each element.   To keep  it 
  292.         simple  we  define  12 elements in  the  array  and  another 
  293.         working pointer named "point".
  294.  
  295.              The "*pet[12]" is new to you so a few words would be in 
  296.         order.  What we have defined is an array of 12 pointers, the 
  297.         first  being "pet[0]",  and the last  "pet[11]".   Actually, 
  298.         since an array is itself a pointer, the name "pet" by itself 
  299.         is a pointer to a pointer.   This is valid in C, and in fact 
  300.         you  can  go  farther  if needed but you  will  get  quickly 
  301.         confused.   I  know  of no limit as to how  many  levels  of 
  302.         pointing are possible,  so a definition such as "int ****pt" 
  303.         is legal as a pointer to a pointer to a pointer to a pointer 
  304.         to an integer type variable, if I counted right.  Such usage 
  305.         is discouraged until you gain considerable experience.
  306.  
  307.              Now that we have 12 pointers which can be used like any 
  308.         other  pointer,  it  is a simple matter to write a  loop  to 
  309.         allocate  a data block dynamically for each and to fill  the 
  310.         respective  fields with any data desirable.   In this  case, 
  311.         the  fields  are  filled with simple data  for  illustrative 
  312.         purposes,  but we could be reading in a  database,  readings 
  313.         from some test equipment, or any other source of data.
  314.  
  315.              A  few fields are randomly picked to receive other data 
  316.         to illustrate that simple assignments can be used,  and  the 
  317.         data is printed out to the monitor.   The pointer "point" is 
  318.         used  in the printout loop only to serve as an illustration, 
  319.  
  320.  
  321.                                   Page 87
  322.  
  323.  
  324.  
  325.  
  326.  
  327.  
  328.  
  329.  
  330.  
  331.                       Chapter 12 - Dynamic Allocation
  332.  
  333.  
  334.         the  data could have been easily printed using the  "pet[n]" 
  335.         means  of definition.   Finally,  all 12 blocks of data  are 
  336.         freed before terminating the program.
  337.  
  338.              Compile  and run this program to aid  in  understanding 
  339.         this  technique.   As stated earlier,  there was nothing new 
  340.         here  about  dynamic  allocation,  only about  an  array  of 
  341.         pointers.
  342.  
  343.                                A LINKED LIST
  344.  
  345.              We  finally  come to the grandaddy of  all  programming 
  346.         techniques as far as being intimidating.   Load the  program 
  347.         DYNLINK.C  for an example of a dynamically allocated  linked 
  348.         list.   It  sounds terrible,  but after a little time  spent 
  349.         with it,  you will see that it is simply another programming 
  350.         technique  made  up  of  simple components  that  can  be  a 
  351.         powerful tool.
  352.  
  353.              In order to set your mind at ease,  consider the linked 
  354.         list  you used when you were a child.   Your sister gave you 
  355.         your birthday present,  and when you opened it,  you found a 
  356.         note that said,  "Look in the hall closet."  You went to the 
  357.         hall closet,  and found another note that said, "Look behind 
  358.         the  TV  set."  Behind the TV you found  another  note  that 
  359.         said,  "Look  under  the  coffee pot."  You  continued  this 
  360.         search,  and finally you found your pair of socks under  the 
  361.         dogs  feeding dish.   What you actually did was to execute a 
  362.         linked  list,  the starting point being the wrapped  present 
  363.         and the ending point being under the dogs feeding dish.  The 
  364.         list ended at the dogs feeding dish since there were no more 
  365.         notes.
  366.  
  367.              In  the program DYNLINK.C,  we will be doing  the  same 
  368.         thing as your sister forced you to do.   We will however, do 
  369.         it  much  faster and we will leave a little pile of data  at 
  370.         each of the intermediate points along the way.  We will also 
  371.         have   the  capability  to  return  to  the  beginning   and 
  372.         retraverse the entire list again and again if we so desire.
  373.  
  374.                             THE DATA DEFINITIONS
  375.  
  376.              This program starts similarly to the last two with  the 
  377.         addition  of the definition of a constant to be used  later.  
  378.         The  structure  is nearly the same as that used in the  last 
  379.         two programs except for the addition of another field within 
  380.         the structure,  the pointer.   This pointer is a pointer  to 
  381.         another  structure  of  this same type and will be  used  to 
  382.         point to the next structure in order.  To continue the above 
  383.         analogy,  this pointer will point to the next note, which in 
  384.         turn will contain a pointer to the next note after that.
  385.  
  386.  
  387.                                   Page 88
  388.  
  389.  
  390.  
  391.  
  392.  
  393.  
  394.  
  395.  
  396.  
  397.                       Chapter 12 - Dynamic Allocation
  398.  
  399.  
  400.  
  401.              We  define three pointers to this structure for use  in 
  402.         the program, and one integer to be used as a counter, and we 
  403.         are ready to begin using the defined structure for  whatever 
  404.         purpose  we  desire.   In  this case,  we  will  once  again 
  405.         generate nonsense data for illustrative purposes.
  406.  
  407.                               THE FIRST FIELD
  408.  
  409.              Using  the  "malloc" function,  we request a  block  of 
  410.         storage on the "heap" and fill it with data.  The additional  
  411.         field in this example, the pointer, is assigned the value of 
  412.         NULL, which is only used to indicate that this is the end of 
  413.         the  list.   We  will  leave  the pointer  "start"  at  this 
  414.         structure,  so  that  it  will always  point  to  the  first 
  415.         structure of the list.   We also assign "prior" the value of 
  416.         "start" for reasons we will see soon.  Keep in mind that the 
  417.         end  points of a linked list will always have to be  handled 
  418.         differently  than those in the middle of a list.   We have a 
  419.         single  element  of  our  list now and  it  is  filled  with 
  420.         representative data.
  421.  
  422.                        FILLING ADDITIONAL STRUCTURES
  423.  
  424.              The  next group of assignments and  control  statements 
  425.         are  included  within a "for" loop so we can build our  list 
  426.         fast  once  it is defined.   We will go through the  loop  a 
  427.         number  of times equal to the constant "RECORDS" defined  at 
  428.         the  beginning  of  our  program.   Each  time  through,  we 
  429.         allocate memory,  fill the first three fields with nonsense, 
  430.         and  fill the pointers.   The pointer in the last record  is 
  431.         given  the  address of this new record because  the  "prior" 
  432.         pointer is pointing to the prior record.  Thus "prior->next" 
  433.         is given the address of the new record we have just  filled.  
  434.         The  pointer in the new record is assigned the value "NULL", 
  435.         and  the  pointer "prior" is given the address of  this  new 
  436.         record  because the next time we create a record,  this  one 
  437.         will  be  the  prior  one at  that  time.   That  may  sound 
  438.         confusing  but it really does make sense if you  spend  some 
  439.         time studying it.
  440.  
  441.              When  we have gone through the "for" loop 6  times,  we 
  442.         will  have  a  list  of 7 structures including  the  one  we 
  443.         generated  prior  to  the loop.   The  list  will  have  the 
  444.         following characteristics.
  445.  
  446.  
  447.         1. "start" points to the first structure in the list.
  448.  
  449.         2. Each structure contains a pointer to the next structure.
  450.  
  451.  
  452.  
  453.                                   Page 89
  454.  
  455.  
  456.  
  457.  
  458.  
  459.  
  460.  
  461.  
  462.  
  463.                       Chapter 12 - Dynamic Allocation
  464.  
  465.  
  466.         3. The last structure has a pointer  that points to NULL and    
  467.            can be used to detect the end.
  468.  
  469.            start->struct1              This diagram should aid in
  470.                   name              understanding the structure of
  471.                   breed             the data at this point.
  472.                   age
  473.                   point->struct2
  474.                          name
  475.                          breed
  476.                          age
  477.                          point->struct3
  478.                                 name
  479.                                 breed
  480.                                 age
  481.                                 point-> . . . . struct7
  482.                                                 name
  483.                                                 breed
  484.                                                 age
  485.                                                 point->NULL
  486.  
  487.  
  488.              It should be clear to you,  if you understand the above 
  489.         structure,  that  it is not possible to simply jump into the 
  490.         middle of the structure and change a few values.   The  only 
  491.         way  to  get  to the third structure is by starting  at  the 
  492.         beginning  and working your way down through  the  structure 
  493.         one  record at a time.   Although this may seem like a large 
  494.         price  to  pay for the convenience of putting so  much  data 
  495.         outside of the program area,  it is actually a very good way 
  496.         to store some kinds of data.
  497.  
  498.             A  word processor would be a good application  for  this 
  499.         type  of data structure because you would never need to have 
  500.         random access to the data.   In actual practice, this is the 
  501.         basic type of storage used for the text in a word  processor 
  502.         with one line of text per record.   Actually, a program with 
  503.         any degree of sophistication would use a doubly linked list.  
  504.         This  would  be  a list with two pointers  per  record,  one 
  505.         pointing down to the next record,  and the other pointing up 
  506.         to the record just prior to the one in question.  Using this 
  507.         kind  of a record structure would allow traversing the  data 
  508.         in either direction.
  509.  
  510.                            PRINTING THE DATA OUT
  511.  
  512.              To print the data out, a similar method is used as that 
  513.         used to generate the data.  The pointers are initialized and 
  514.         are  then  used  to go from record  to  record  reading  and 
  515.         displaying   each  record  one  at  a  time.    Printing  is 
  516.         terminated when the NULL on the last record is found, so the 
  517.  
  518.  
  519.                                   Page 90
  520.  
  521.  
  522.  
  523.  
  524.  
  525.  
  526.  
  527.  
  528.  
  529.                       Chapter 12 - Dynamic Allocation
  530.  
  531.  
  532.         program  doesn't even need to know how many records  are  in 
  533.         the list.   Finally, the entire list is deleted to make room 
  534.         in  memory  for any additional data that may be  needed,  in 
  535.         this case, none.  Care must be taken to assure that the last 
  536.         record is not deleted before the NULL is checked.   Once the 
  537.         data is gone,  it is impossible to know if you are  finished 
  538.         yet.
  539.  
  540.                MORE ABOUT DYNAMIC ALLOCATION AND LINKED LISTS
  541.  
  542.              It  is  not difficult,  and it is not trivial,  to  add 
  543.         elements into the middle of a linked lists.  It is necessary 
  544.         to create the new record,  fill it with data,  and point its 
  545.         pointer to the record it is desired to precede.   If the new 
  546.         record  is  to be installed between the  3rd  and  4th,  for 
  547.         example,  it is necessary for the new record to point to the 
  548.         4th record,  and the pointer in the 3rd record must point to 
  549.         the new one.  Adding a new record to the beginning or end of 
  550.         a  list are each special cases.   Consider what must be done 
  551.         to add a new record in a doubly linked list. 
  552.  
  553.              Entire books are written describing different types  of 
  554.         linked lists and how to use them,  so no further detail will 
  555.         be  given.   The amount of detail given should be sufficient 
  556.         for a beginning understanding of C and its capabilities.
  557.  
  558.                        ANOTHER NEW FUNCTION - CALLOC
  559.  
  560.              One  more  function must  be  mentioned,  the  "calloc" 
  561.         function.   This  function  allocates a block of memory  and 
  562.         clears  it  to  all  zeros  which  may  be  useful  in  some 
  563.         circumstances.   It is similar to "malloc" and will be  left 
  564.         as an exercise for you to read about and use "calloc" if you 
  565.         desire.
  566.  
  567.         PROGRAMMING EXERCISES
  568.  
  569.         1.  Rewrite the example program STRUCT1.C from chapter 11 to 
  570.             dynamically allocate the two structures.
  571.  
  572.         2.  Rewrite the example program STRUCT2.C from chapter 11 to 
  573.             dynamically allocate the 12 structures.
  574.  
  575.  
  576.  
  577.  
  578.  
  579.  
  580.  
  581.  
  582.  
  583.  
  584.  
  585.                                   Page 91
  586.  
  587.